﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Module_ArticleController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index(string actionId)
        {
            this.ValidateRequest = false;
            ViewData["id"] = actionId;
            return View("Index");//页面地址
        }

        /// <summary>
        /// 返回文章列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
            string sort = (string)Utils.GetQueryAndFormString("sort", this, 100, 0, DataType.Str);
            string search = (string)Utils.GetQueryAndFormString("s", this, 40, 0, DataType.Str);
            SortEntity sortEntity = null;

            List<SortEntity> sortList = new List<SortEntity>();
            sortList = (List<SortEntity>)JsonConvert.DeserializeObject(sort, typeof(List<SortEntity>));
            if (sortList.Count > 0)
            {
                sortEntity = sortList[0];
            }

            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex / pageSize + 1;
            qp.PageSize = pageSize;
            qp.Where = string.Concat("channelid=", actionId);
            if (!string.IsNullOrEmpty(search))
            {
                qp.Where = string.Concat(qp.Where," and title like '",search,"%'");
            }
            if (sortEntity != null)
                qp.Orderfld = string.Concat(sortEntity.Property, " ", sortEntity.Direction);
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
            qp.ReturnFields = "Id,ChannelId,Path ,Title,AddDate,IsImg ,SourceFrom,ViewNum,SupportNum,Enabled,IsPass";
            List<Module_ArticleEntity> module_articleList = Module_ArticleSv.List(qp, out recordNum);
            returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(module_articleList, Formatting.Indented, jsDataConvert), "}");
            return returnJson;
        }

        /// <summary>
        /// 返回标签列表
        /// </summary>
        /// <returns>json</returns>
        public string TagList(string actionId)
        {
            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
            string query = (string)Utils.GetQueryAndFormString("query", this, 9, 0, DataType.Str);
            QueryParam qp = new QueryParam();
            qp.PageIndex = pageIndex / pageSize + 1; ;
            qp.PageSize = pageSize;
            if (string.IsNullOrEmpty(query))
            {
               
                    IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
                    int intId = Utils.StringToInt(actionId, 0);
                    Module_ArticleEntity module_article = Module_ArticleSv.Look(intId);
                    if (!string.IsNullOrEmpty(module_article.Tags))
                    {
                        qp.Where = string.Concat("id in (", module_article.Tags, ")");
                    }
                    else
                    {
                        qp.Where = "1=2";
                    }

            }
            else
                qp.Where = string.Concat("tagName like'", query, "%'");
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Normal_TagsEntity> Normal_TagsSv = ServiceBuilder.BuildNormal_TagsService();
            List<Normal_TagsEntity> normal_tagsList = Normal_TagsSv.List(qp, out recordNum);
            returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(normal_tagsList, Formatting.Indented, jsDataConvert), "}");
            return returnJson;

        }

        /// <summary>
        /// 查看文章 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
            int intId=Utils.StringToInt(actionId,0);
            Module_ArticleEntity module_article = Module_ArticleSv.Look(intId);
            if (module_article != null)
            {
                module_article.checkboxgrupflag = module_article.Flag;
                IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                jsDataConvert.DateTimeFormat = "yyyy-MM-dd hh:mm:ss";
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(module_article, Formatting.None,jsDataConvert), "}");
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        [ValidateInput(false)]
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Module_ArticleEntity module_article = new Module_ArticleEntity();
                module_article.DataTable_Action = DataTableAction.Update;
                module_article.Id = intId;
                module_article.ChannelId = (Int32)Utils.GetQueryAndFormString("ChannelId", this, 10,  1 , DataType.Int);
                module_article.Path = (string)Utils.GetQueryAndFormString("Path", this, 10,  1 , DataType.CharAndNum);
                module_article.Title = (String)Utils.GetQueryAndFormString("Title", this, 150,  1 , DataType.Str);
                module_article.TColor = (String)Utils.GetQueryAndFormString("TColor", this, 8,  0, DataType.Str);
                module_article.AddDate = (DateTime)Utils.GetQueryAndFormString("AddDate", this, 23,  1 , DataType.Dat);
                module_article.Summary = (String)Utils.GetQueryAndFormString("Summary", this, 360,  0 , DataType.Str);
                module_article.Editor = (String)Utils.GetQueryAndFormString("Editor", this, 20, 0 , DataType.Str);
                module_article.Author = (String)Utils.GetQueryAndFormString("Author", this, 30,  0, DataType.Str);
                module_article.Tags = (String)Utils.GetQueryAndFormString("Tags", this, 60,  0, DataType.Str);
                module_article.Tags = module_article.Tags.Replace("\"", "").Replace("[", "").Replace("]", "");
                module_article.ViewNum = (Int32)Utils.GetQueryAndFormString("ViewNum", this, 10,  0 , DataType.Int);
                module_article.IsPass = (Int32)Utils.GetQueryAndFormString("IsPass", this,2, 1, DataType.Int);
                module_article.IsImg = (bool)Utils.GetQueryAndFormString("IsImg", this, 6,  1 , DataType.Bool);
                module_article.Img = (String)Utils.GetQueryAndFormString("Img", this, 150,  0 , DataType.Str);
                module_article.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10,  1 , DataType.Int);
                module_article.UserId = (Int32)Utils.GetQueryAndFormString("UserId", this, 10,  1 , DataType.Int);
                module_article.ReadGroup = (Int32)Utils.GetQueryAndFormString("ReadGroup", this, 10,  1 , DataType.Int);
                module_article.SourceFrom = (String)Utils.GetQueryAndFormString("SourceFrom", this, 300, 0, DataType.Str);
                module_article.TextContent = (String)Utils.GetQueryAndFormString("TextContent", this, 2147483647,  1 , DataType.Str);
                module_article.WriteComment = (Int32)Utils.GetQueryAndFormString("WriteComment", this, 10,  0 , DataType.Int);
                module_article.ReadComment = (Int32)Utils.GetQueryAndFormString("ReadComment", this, 10,  0 , DataType.Int);
                module_article.SupportNum = (Int32)Utils.GetQueryAndFormString("SupportNum", this, 10,  0 , DataType.Int);
                module_article.AgainstNum = (Int32)Utils.GetQueryAndFormString("AgainstNum", this, 10,  0 , DataType.Int);
                module_article.Enabled = (bool)Utils.GetQueryAndFormString("Enabled", this, 6,  1 , DataType.Bool);
                module_article.IsCreateIndex = (bool)Utils.GetQueryAndFormString("IsCreateIndex", this, 6, 0, DataType.Bool);
                module_article.Remark = (String)Utils.GetQueryAndFormString("Remark", this, 2147483647, 0, DataType.Str);
                module_article.Flag = (String)Utils.GetQueryAndFormString("checkboxgrupflag", this, 50, 0, DataType.Str);
                int topNum = (Int32)Utils.GetQueryAndFormString("checkboxgruptoptime", this, 10, 0, DataType.Int);
                module_article.IsAutoImg = (String)Utils.GetQueryAndFormString("IsAutoImg", this, 2, 0, DataType.Str);
                if (module_article.AddDate == null)
                {
                    module_article.AddDate = DateTime.Now;
                }
                if (module_article.IsAutoImg == "1")
                {
                    if (string.IsNullOrEmpty(module_article.Img))
                    {
                        module_article.Img = GetImg(module_article.TextContent);
                    }
                }
                if(topNum>0)
                module_article.TopTime = module_article.AddDate.AddDays(topNum);
                IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
                if (Module_ArticleSv.Update(module_article) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
           
            return returnJson;
        }

        /// <summary>
        /// 新增文章
        /// </summary>
        /// <returns>json</returns>
        [ValidateInput(false)]
        public string Insert(string actionId)
        {
            int channelId = 0;
            channelId = Utils.StringToInt(actionId.ToString(), 0);
           if (channelId != 0)
           {
               IDataService<Normal_ChannelEntity> channelSv = ServiceBuilder.BuildNormal_ChannelService();
               Normal_ChannelEntity channel = channelSv.Look(channelId);
               
               if (channel != null)
               {
                   Module_ArticleEntity module_article = new Module_ArticleEntity();

                   module_article.DataTable_Action = DataTableAction.Insert;
                   module_article.ChannelId = channelId;
                   module_article.Path = channel.Path;
                   module_article.Title = (String)Utils.GetQueryAndFormString("Title", this, 150, 1, DataType.Str);
                   module_article.TColor = (String)Utils.GetQueryAndFormString("TColor", this, 8, 0, DataType.Str);
                   module_article.AddDate = (DateTime)Utils.GetQueryAndFormString("AddDate", this, 360, 0, DataType.Dat);
                   module_article.Summary = (String)Utils.GetQueryAndFormString("Summary", this, 360, 0, DataType.Str);
                   module_article.Editor = (String)Utils.GetQueryAndFormString("Editor", this, 20, 0, DataType.Str);
                   module_article.Author = (String)Utils.GetQueryAndFormString("Author", this, 30, 0, DataType.Str);
                   module_article.Tags = (String)Utils.GetQueryAndFormString("Tags", this, 60, 0, DataType.Str);
                   module_article.Tags = module_article.Tags.Replace("\"", "").Replace("[", "").Replace("]", "");
                   
                   module_article.ViewNum =  (Int32)Utils.GetQueryAndFormString("ViewNum", this, 10, 1, DataType.Int);
                   module_article.IsPass = (Int32)Utils.GetQueryAndFormString("IsPass", this, 2, 1, DataType.Int);
                   module_article.IsImg = (bool)Utils.GetQueryAndFormString("IsImg", this, 6, 1 , DataType.Bool);
                   module_article.Img = (String)Utils.GetQueryAndFormString("Img", this, 150, 0, DataType.Str);
                   module_article.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10, 0, DataType.Int);
                   module_article.UserId =CMN.Framework.UserData.GetUserData.UserID;
                   module_article.ReadGroup = (Int32)Utils.GetQueryAndFormString("ReadGroup", this, 10, 0, DataType.Int);
                   module_article.SourceFrom = (String)Utils.GetQueryAndFormString("SourceFrom", this, 300, 0, DataType.Str);
                   module_article.TextContent = (String)Utils.GetQueryAndFormString("TextContent", this, 2147483647, 1, DataType.Str);
                   module_article.WriteComment = (Int32)Utils.GetQueryAndFormString("WriteComment", this, 10, 0, DataType.Int);
                   module_article.ReadComment = (Int32)Utils.GetQueryAndFormString("ReadComment", this, 10, 0, DataType.Int);
                   module_article.SupportNum = (Int32)Utils.GetQueryAndFormString("SupportNum", this, 10,  1 , DataType.Int);
                   module_article.AgainstNum =  (Int32)Utils.GetQueryAndFormString("AgainstNum", this, 10,  1 , DataType.Int);
                   module_article.Enabled = (bool)Utils.GetQueryAndFormString("Enabled", this, 6, 1, DataType.Bool);
                   module_article.Remark = (String)Utils.GetQueryAndFormString("Remark", this, 2147483647, 0, DataType.Str);
                   module_article.Flag = (String)Utils.GetQueryAndFormString("checkboxgrupflag", this, 50, 0, DataType.Str);
                   int topNum = (Int32)Utils.GetQueryAndFormString("checkboxgruptoptime", this, 10, 0, DataType.Int);
                   module_article.IsAutoImg  = (String)Utils.GetQueryAndFormString("IsAutoImg", this, 2, 0, DataType.Str);
                   if (module_article.AddDate == null)
                   {
                       module_article.AddDate = DateTime.Now;
                   }
                   if (module_article.IsAutoImg == "1")
                   {
                       if (string.IsNullOrEmpty(module_article.Img))
                       {
                           module_article.Img = GetImg(module_article.TextContent);
                       }
                   }
                   if (topNum > 0)
                       module_article.TopTime = module_article.AddDate.AddDays(topNum);
                   IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
                   if (Module_ArticleSv.Insert(module_article) == "")
                   {
                       returnJson = "{success:'true'}";
                   }
                   else
                       returnJson = "{success:'false'}";
               }
               else
               {
                   returnJson = "{success:'false',message:'栏目id错误'}";
               }

           }
           else
           {
               returnJson = "{success:'false',message:'栏目id错误'}";
           }
            return returnJson;
        }

        public string GetImg(string content)
        {
           
            string _LocalFileUrl = Utils.GetFirstImg(content);
            if (string.IsNullOrEmpty(_LocalFileUrl))
            {
                return "";
            }
            try
            {
                System.Drawing.Image getImage = System.Drawing.Image.FromFile(Utils.GetMapPath(_LocalFileUrl));
                if (getImage.Width < 300)
                {
                    return _LocalFileUrl;
                }
                string SavePath = "/Upload/";
                SavePath = SavePath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                Utils.CreateDir(Utils.GetMapPath(SavePath));
                string fileType = _LocalFileUrl.Substring(_LocalFileUrl.LastIndexOf('.'));

                System.Guid guid = new Guid();
                guid = Guid.NewGuid();
                SavePath += guid.ToString();

                SavePath += fileType;
                string saveAllPath = Utils.GetMapPath(SavePath);
                ImageHelper imgHelper = new ImageHelper();
                System.Drawing.Image newImag = imgHelper.ScaleFixWidth(getImage, 300);
                newImag.Save(saveAllPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                return SavePath;
            }
            catch (Exception ex)
            {
                AppLog.Write(ex.Message, AppLog.LogMessageType.Error, ex);
                return "";
            }
            
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Module_ArticleEntity module_article = new Module_ArticleEntity();
                module_article.Id = intId;
                IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
                if (Module_ArticleSv.Delete(module_article) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        public string UpdateList(string actionId)
        {
            string idList = (string)Utils.GetQueryAndFormString("id", this, MethodType.Get, 100, 1, DataType.Str);
            string updateValue = string.Empty;
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(idList))
            {


                switch (actionId)
                {
                    case "enabled":
                        {
                            updateValue = " Enabled=1 ";
                            break;
                        }
                    case "disenabled":
                        {
                            updateValue = " Enabled=0 ";
                            break;
                        }
                    case "check":
                        {
                            updateValue = " IsPass=1 ";
                            break;
                        }
                    case "uncheck":
                        {
                            updateValue = " IsPass=0 ";
                            break;
                        }
                    case "inrecycle":
                        {
                            updateValue = " IsPass=2 ";
                            break;
                        }
                    case "outrecycle":
                        {
                            updateValue = " IsPass=1 ";
                            break;
                        }

                    default:
                        {
                            return returnJson = "{success:'false',message:'参数类型不正确'}";
                            break;
                        }
                }
               

            }
            else
            {
                return returnJson = "{success:'false',message:'参数类型不正确'}";

            }
            IUpdateDataService<Module_ArticleEntity> Module_ArticleSv = (IUpdateDataService<Module_ArticleEntity>)ServiceBuilder.BuildModule_ArticleService();
            if (Module_ArticleSv.UpdateList(idList, updateValue)=="")
            {
                returnJson = "{success:'true'}";
            }
            else
                returnJson = "{success:'false'}";

            return returnJson;

        }

        /// <summary>
        /// 批量删除文章
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Module_ArticleEntity> Module_ArticleSv = ServiceBuilder.BuildModule_ArticleService();
                if (Module_ArticleSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
